package com.ruoyi.partybuilding.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.partybuilding.domain.Review;
import com.ruoyi.partybuilding.domain.ReviewStaffs;
import com.ruoyi.partybuilding.domain.vo.ReviewStatVo;
import com.ruoyi.partybuilding.service.impl.OrgServiceImpl;
import com.ruoyi.partybuilding.service.impl.ReviewServiceImpl;
import com.ruoyi.partybuilding.service.impl.ReviewUserServiceImpl;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.partybuilding.domain.ReviewUser;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.*;

import com.ruoyi.partybuilding.common.*;
/**
 * 评议用户Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "评定结果详情")
@RestController
@RequestMapping("/partybuilding/ReviewUser")
public class ReviewUserController extends  EQueryController<ReviewUser>
{
    @Resource
    OrgServiceImpl orgService;
    @Resource
    ReviewServiceImpl reviewService;

    @Resource
    ReviewUserServiceImpl reviewUserService;

    @ApiOperation(value = "评定明细，组织评定列表",notes = "评定明细，按被评人统计,组织评定列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @GetMapping("/listStat")
    public R<List<ReviewStatVo>> listStat(ReviewStatVo vo){
        if(vo.getReviewId()==null)
            return  R.fail("参数错误reviewId");
        return reviewService.statReview(vo);
    }

    @ApiOperation("评定明细导出")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @Log(title = "评议用户", businessType = BusinessType.EXPORT)
    @PostMapping("/expListStat")
    public void expListStat(HttpServletResponse response, ReviewStatVo vo) {
        var re= reviewService.statReview(vo);
        var util = new ExcelUtil(tClass);
        util.exportExcel(response, re.getData(), "评议明细数据记录_"+ DateUtil.now());
    }

    @ApiOperation(value = "评定结果汇总,评定结果",notes = "评定结果汇总,按组织评定结果进行汇总")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @GetMapping("/reviewResultStat")
    public R<List<ReviewStatVo>> reviewResultStat(Long reviewId) {
        if(reviewId==null)
            return R.fail("评议id错误");
        var re = reviewUserService.reviewResultStat(reviewId, 2);
        return R.ok(re);
    }
    /**
     * 查询评议用户列表
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReviewUser review, PageDomain pageRequest) {

        return super.list(review, pageRequest);
    }

    @ApiOperation(value = "用户评定详情列表",notes = "展示我待评定和已评定的用户列表,必须参数：评议reviewId,评定人userId")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @GetMapping("/reviewUserList")
    public TableDataInfoRows<ReviewUser> reviewUserList(ReviewUser review, PageDomain pageRequest){
        var userId =review.getUserId();
        var reviewUserId = review.getReviewedUser();
        var reviewId = review.getReviewId();
        review.setUserId(userId);
        if(userId==null||userId<1)
            return TableDataInfoRows.toFail("评定人错误");
        if(reviewId==null||reviewId<1)
            return TableDataInfoRows.toFail("评议id错误");
        var isUser=queryHelper.queryable(ReviewStaffs.class)
                .where(p->p.eq(ReviewStaffs::getReviewId,reviewId).eq(ReviewStaffs::getType,1).eq(ReviewStaffs::getUserId,userId)).any();
        if(!isUser)
            return TableDataInfoRows.toEmpty("非评定人");
        var page = queryHelper.queryable(ReviewStaffs.class)
                .leftJoin(ReviewUser.class, (p, p2) -> {
                    p.eq(p2, ReviewStaffs::getReviewId, ReviewUser::getReviewId).eq(p2,ReviewStaffs::getUserId,ReviewUser::getReviewedUser);
                    p2.eq(true,ReviewUser::getUserId,userId);
                })
                .where(p->p.eq(ReviewStaffs::getType,0))
                .select(ReviewUser.class, (p, p2) -> {
                    p.column(ReviewStaffs::getReviewId);
                    p.columnAs(ReviewStaffs::getUserId, "reviewedUser");
                    p.columnAs(ReviewStaffs::getUserName, "reviewedUserName");
                    p.columnAs(ReviewStaffs::getDeptName,"reviewedUserDeptName");
                    p.columnAs(ReviewStaffs::getDeptId,"reviewedUserDept");
                    p.sqlNativeSegment("{1} user_id",x->x.expression(ReviewStaffs::getUserId).value(userId));

                    p2.columnAll();
                    p2.columnIgnore(ReviewUser::getUserId);
                    p2.columnIgnore(ReviewUser::getReviewId);
                    p2.columnIgnore(ReviewUser::getReviewedUser);
                    p2.columnIgnore(ReviewUser::getReviewedUserName);
                    p2.columnIgnore(ReviewUser::getReviewedUserDept);
                    p2.columnIgnore(ReviewUser::getReviewedUserDeptName);
                })
                .whereObject(review)
                .orderByDesc(p->p.column(ReviewUser::getId))
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        return toTableDataInfoRows(page);
    }
    @ApiOperation(value = "我的评定列表",notes = "展示我待评定和已评定的用户列表,必须参数：评议reviewId,评定人为当前登陆人")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:list')")
    @GetMapping("/myReviewUsers")
    public TableDataInfoRows<ReviewUser> myReviewUsers(ReviewUser review, PageDomain pageRequest) {
        review.setUserId(getUserId());
        return  reviewUserList(review,pageRequest);
    }


    /**
     * 导出评议用户列表
     */
    @ApiOperation("导出")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:export')")
    @Log(title = "评议用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReviewUser review, PageDomain pageRequest) {
        super.export(review,pageRequest,null,response);
    }



    /**
     * 获取评议用户详细信息
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:query')")
    @GetMapping(value = "/{id}")
    public R<ReviewUser> getInfo(@PathVariable("id") Long id) {
        return super.getInfo(id);
    }


    /**
     * 新增评议用户
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:add')")
    @Log(title = "评议用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<Long> add(@RequestBody ReviewUser review) {
        return super.add(review);
    }

    /**
     * 修改评议用户
     */
    @ApiOperation("编辑")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:edit')")
    @Log(title = "评议用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public R<Long> edit(@RequestBody ReviewUser review) {
        return super.edit(review);
    }
    @ApiOperation(value = "新增评定",notes = "评议id,被评人，评价")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:edit')")
    @Log(title = "评定", businessType = BusinessType.INSERT)
    @PostMapping("/comment")
    public R<Long> comment(@RequestBody ReviewUser reviewUser ) {
        Long reviewId=reviewUser.getReviewId();
        Long reviewUserId=reviewUser.getReviewedUser();
        Long grade=reviewUser.getGrade();
        var review = queryHelper.queryable(Review.class).include(p->p.many(Review::getStaffs)).whereById(reviewId).firstOrNull();
        if (review == null||review.getStatus()!=0)
            return R.fail("无法找到对应评议或不可评定");
        var userId=getUserId();
        if (CollectionUtil.isEmpty(review.getStaffs())
                || review.getStaffs().stream().noneMatch(p ->p.getType()==1&& Objects.equals(p.getUserId(), userId))) {
            return R.fail("非评价列表用户");
        }

        var isAny = queryHelper.queryable(ReviewUser.class)
                .where(p -> p.eq(ReviewUser::getReviewId, reviewId).eq(ReviewUser::getType,0)
                        .eq(ReviewUser::getReviewedUser, userId).eq(ReviewUser::getUserId, userId)).any();
        if (isAny)
            return R.fail("重复评议");

        var ru = setReviewUser(reviewUser, 0l);
        queryHelper.query().insertable(ru).executeRows(true);
        return R.ok(ru.getId());
    }
    @ApiOperation(value = "新增组织评定",notes = "组织评定后会设置状态为已结束")
    @PreAuthorize("@ss.hasPermi('partybuilding:Review:edit')")
    @Log(title = "评定", businessType = BusinessType.INSERT)
    @PostMapping("/orgComment")
    @Transactional
    public R<Long> orgComment(@RequestBody @Validated ReviewUser reviewUser) {
        var review = queryHelper.queryable(Review.class).whereById(reviewUser.getReviewId()).firstOrNull();
        if (review == null)
            return R.fail("无法找到对应评议");
        var isAny = queryHelper.queryable(ReviewUser.class)
                .where(p -> p.eq(ReviewUser::getReviewId, reviewUser.getReviewId())
                        .eq(ReviewUser::getType, 2).eq(ReviewUser::getReviewedUser,reviewUser.getReviewedUser()))
                .any();
        if (isAny)
            return R.fail("重复评议");

        var ru = setReviewUser(reviewUser,2l);
        queryHelper.query().insertable(ru).executeRows(true);
        review.setStatus(1);
        queryHelper.query().updatable(review).executeRows();
        return R.ok(ru.getId());
    }


    private ReviewUser setReviewUser(ReviewUser ru,Long type) {
        ru.setUserId(getUserId());
        ru.setUserName(getUsername());
        ru.setDeptId(getDeptId());
        ru.setDeptName(orgService.deptVoGet(getDeptId()).getData().getDeptName());
        ru.setCreatedTime(new Date());
        ru.setType(type);
        return ru;
    }

    /**
     * 删除评议用户
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:ReviewUser:remove')")
    @Log(title = "评议用户", businessType = BusinessType.DELETE)
	@PostMapping("remove/{ids}")
    public R<Long> remove(@PathVariable Long[] ids) {
        return super.remove(ids);
    }



}
